﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ExpreRec.DataAccess.Util
{
    /// <summary>
    /// 将SqlParam的参数值转换为安全的参数值的工具函数
    /// </summary>
    public abstract class SQLParamConverter
    {
        /// <summary>
        /// 转换object到SqlParam安全的object
        /// </summary>
        /// <param name="o">object</param>
        /// <returns>SqlParam安全的object</returns>
        public static object ObjectToSqlObject(object o)
        {
            if (o == null)
                return DBNull.Value;
            else return o;
        }

        /// <summary>
        /// 转换int到SqlParam安全的object
        /// </summary>
        /// <param name="o">int</param>
        /// <returns>SqlParam安全的object</returns>
        public static object ObjectToSqlObject(int o)
        {
            //注意如果o为-1表示存入数据库为空
            if (o == -1)
                return DBNull.Value;
            else return o;
        }

        /// <summary>
        /// 转换DateTime到SqlParam安全的object
        /// </summary>
        /// <param name="o">object</param>
        /// <returns>SqlParam安全的object</returns>
        public static object ObjectToSqlObject(DateTime o)
        {
            if (o.Ticks == 0)
                return DBNull.Value;
            else return o;
        }

        /// <summary>
        /// 把普通字符串转换为like的条件字符串
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>like的条件字符串</returns>
        public static string ObjectToSqlLikeObject(string s)
        {
            if (s == null)
                return "%%";
            else return string.Format("%{0}%", s);
        }

        /// <summary>
        /// 将list类型转换为Sql集合
        /// </summary>
        /// <param name="s">list类型</param>
        /// <returns>Sql集合</returns>
        public static string ListToSqlSetObject(IList<string> s)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\'\'");
            if (s != null)
            {
                foreach (string str in s)
                    sb.Append(string.Format(", \'{0}\'", str));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 将list类型转换为Sql集合
        /// </summary>
        /// <param name="s">list类型</param>
        /// <returns>Sql集合</returns>
        public static string ListToSqlSetObject(IList<int> s)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("0");
            if (s != null)
            {
                foreach (int i in s)
                    sb.Append(string.Format(", {0}", i.ToString()));
            }
            return sb.ToString();
        }
    }
}
